package atom.core3.apache.http4;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

import atom.core0.exception.BizException;
import atom.core0.exception.UnknowStateException;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:HttpClient
 * </p>
 * <p>
 * Copyright: Copyright (c) 2010
 * </p>
 * <p>
 * </p>
 * 
 * @author 赵明才
 * @version 1.0
 */
public class HttpClientMultipartAgent extends HttpClientAgent
{
	private Map parmmap = new HashMap();
	public  HttpClientMultipartAgent(String charset, int connecttimeout, int readtimeout) 
	{
		super(charset, connecttimeout, readtimeout);
	}

	public void addParm(String name, String value)
	{
		StringBody sp = new StringBody(name,ContentType.MULTIPART_FORM_DATA);
		parmmap.put(name, sp);
	}

	// new File( " ./temp/test.txt " )
	public void addFile(String name, File file) throws Exception
	{
		FileBody fileBody = new FileBody(file);
		parmmap.put(name, fileBody);;

	}

	public void sendPost(String url) throws BizException, UnknowStateException
	{

		postgetMethod = new HttpPost(url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		Iterator it = parmmap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String key = (String) entry.getKey();
			 ContentBody value =  (ContentBody)entry.getValue();
			builder.addPart(key, value);
		}		
		
		HttpEntity entity = builder.build();
		//
		HttpPost postMethod = (HttpPost) postgetMethod;
		postMethod.setEntity(entity);
		postUrl(url);

	}

}
